import axios from 'axios';
import qs from "query-string";
import { grantTypes, client } from '@/config/website.json'
import type { LoginData, OAuth2AccessToken, UserToken } from '@/types/modules/auth'
import { Pageable, Pagination } from '@/types/global'

const contentPath = '/auth/oauth'

export function login(data: LoginData) {
  const grantType = grantTypes?.password || 'password'
  const basicAuth = `Basic ${window.btoa(client.default)}`
  return axios.post<OAuth2AccessToken>(`${contentPath}/token`, qs.stringify(data), {
    headers: {
      Authorization: basicAuth,
      rememberMe: `${data.rememberMe || false}`
    },
    params: {
      grant_type: grantType,
    },
  })
}

export function logout() {
  return axios.post<boolean>(`${contentPath}/logout`)
}

export function revokeToken(accessToken: string) {
  return axios.post<boolean>(`${contentPath}/revoke/token`, null, {
    params: {
      accessToken
    }
  })
}

export function tokenWithPagination(pageable: Pageable) {
  return axios.get<Pagination<UserToken>>(`${contentPath}/pagination`, {
    params: {
      ...pageable
    }
  })
}
